from flask import Flask, render_template
import pymysql
import random
import json
import main
from threading import Thread

app = Flask(__name__)



def file_config():  # 获取数据库连接的基本信息
    file = open('./config.txt', mode='r', encoding='utf-8')
    file_database = open('database.txt', 'r')
    try:
        content = eval(file.read())
        database = eval(file_database.read())
        content['database'] = database['database']
        file.close()
        file_database.close()
        return content
    except Exception as err:
        file.close()
        file_database.close()
        return "数据库配置文件错误，请检查config.txt文件"


# mysql 拥有创建数据库的权限
host = file_config()['host']
user = file_config()['user']
password = file_config()['password']
port = int(file_config()['port'])
db = file_config()['database']
con = pymysql.connect(host=host, user=user, passwd=password, port=port,db=db)
cur = con.cursor()


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/a_word_from')
def a_word_from():  # 一言语录
    result = cur.execute("select * from A_WORD_FROM")
    result = cur.fetchall()
    for content in result:
        number = random.randint(1, len(result))
        if number == random.randint(1, int(len(result)/2)):
            break
    text = {"text": content[0]}
    jsons = json.loads(str(text).replace("'", '"'))
    return jsons


@app.route('/lick_the_dog_diary')
def lick_the_dog_diary():  # 舔狗日记
    result = cur.execute("select * from LICK_THE_DOG_DIARY")
    result = cur.fetchall()
    for content in result:
        number = random.randint(1, len(result))
        if number == random.randint(1, int(len(result)/2)):
            break
    text = {"text": content[0]}
    jsons = json.loads(str(text).replace("'", '"'))
    return jsons


@app.route('/tainted_chicken_soup')
def tainted_chicken_soup():  # 毒鸡汤
    result = cur.execute("select * from TAINTED_CHICKEN_SOUP")
    result = cur.fetchall()
    for content in result:
        number = random.randint(1, len(result))
        if number == random.randint(1, int(len(result)/2)):
            break
    text = {"text": content[0]}
    jsons = json.loads(str(text).replace("'", '"'))
    return jsons


@app.route('/get.html')
def get():  # 获取数据
    return render_template('get.html'),main.start()


@app.route('/distinct.html')
def distinct():  # 去除数据库当中的重复数据
    return render_template('distinct.html'),main.distinct()


if __name__ == '__main__':
    app.run()
